/*
 * Created by CZJ on July 19, 2019.
 * @description 图片预览组件
 */
import React, { PureComponent } from 'react';
import { Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import Gallery from 'react-native-image-gallery';
import _ from 'lodash';

import { adapt } from '~/utils/ScreenAdapter';

class ImageGallery extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      index: 0,
      data: [],
    };
  }

  open = (index, images) => {
    let data = images.map(v =>
      _.isString(v) && v.startsWith('http')
        ? { source: { uri: v } }
        : { source: v }
    );
    this.setState({ visible: true, index, data });
  };

  onClose = () => {
    this.setState({ visible: false });
  };

  render() {
    return (
      <Modal visible={this.state.visible}>
        <TouchableOpacity style={styles.back} onPress={this.onClose}>
          <Text style={{ color: '#fff' }}>返回</Text>
        </TouchableOpacity>
        <Gallery
          style={styles.gallery}
          images={this.state.data}
          initialPage={this.state.index}
          onPageSelected={index => this.setState({ index })}
        />
        <TouchableOpacity onPress={this.onClose}>
          <View style={styles.touchHide} />
        </TouchableOpacity>
        <View style={styles.index}>
          <Text style={{ color: '#fff' }}>
            {this.state.index + 1}/{this.state.data.length}
          </Text>
        </View>
      </Modal>
    );
  }
}

export default ImageGallery;

const styles = StyleSheet.create({
  gallery: {
    flex: 1,
    backgroundColor: 'black',
  },
  back: {
    position: 'absolute',
    padding: adapt(20),
    paddingTop: adapt(40),
    zIndex: 100,
  },
  index: {
    position: 'absolute',
    bottom: adapt(30),
    left: 0,
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  touchHide: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    top: 0,
    left: 0,
    zIndex: 10000,
  },
});
